package com.resource;

import org.springframework.beans.factory.xml.DefaultDocumentLoader;
import org.springframework.beans.factory.xml.DocumentLoader;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;
import java.io.InputStream;

public class FileSourceLoader {

    public static void main(String[] args) throws Exception {

        // 读取资源文件
        Resource resource = new ClassPathResource("xmlContext.xml");
        EncodedResource encodedResource = new EncodedResource(resource);

        //从EncodedResource中获取对应的 InputStream 并构造 InputSource
        InputStream inputStream = encodedResource.getResource().getInputStream();
        InputSource inputSource = new InputSource(inputStream);

        // 解析xml
        DocumentLoader documentLoader = new DefaultDocumentLoader();
        PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
        ResourceEntityResolver entityResolver = new ResourceEntityResolver(patternResolver);
        Document document = documentLoader.loadDocument(inputSource, entityResolver, new DefaultHandler(), 3, false);

        Element root = document.getDocumentElement();
        NodeList nodeList = root.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (!(node instanceof Element)) {
                continue;
            }

            Element element = (Element) node;
            if (!"bean".equals(element.getNodeName())) {
                continue;
            }

            String id = element.getAttribute("id");
            String clazz = element.getAttribute("class");
            String scope = element.getAttribute("scope");

            System.out.println("测试结果 beanName：" + id + ", beanClass：" + clazz + ", scope：" + scope);
        }


    }

    // public static void resolveXmlBySAX(String xmlName) {
    //     InputStream inputStream = encodedResource.getResource().getInputStream();
    //
    // }

}
